<template>
  <view class="position-page">
    <view class="position-container">
      <!-- 职位卡片列表 -->
      <view class="position-list">
        <view 
          v-for="item in positionList" 
          :key="item.rowid"
          class="position-card"
          :style="{ backgroundColor: getCardBgColor(item['686f2308f11e0126aeb367d7']) }"
          @tap="handlePositionClick(item)">

          <view class="position-header">
            <view class="position-title">
              <!-- 角色 -->
              <text class="title-text">{{item['686f2308f11e0126aeb367d7'] || '未知角色'}}</text>
              <!-- 个数 -->
              <text class="position-count">{{item['686e48ea1f42f2639e1b907b'] || 0}}位</text>
            </view>
            <!-- 是否报价 -->
            <view class="price-tag" :class="{'reported': getPositionQuoteStatus(item['686f2308f11e0126aeb367d7']) }">
              {{ getPositionQuoteStatus(item['686f2308f11e0126aeb367d7']) ? '已报价' : '未报价' }}
            </view>
          </view>
          <!-- 要求 -->
          <view class="position-desc">
            <text v-if="item['6880ba578c409b88b851aa8b'] && item['6880ba578c409b88b851aa8b'].length > 0">{{item['6880ba578c409b88b851aa8b'][0]}}</text>
          </view>
          <view class="divider"></view>
          <view class="position-info">
            <view class="info-item">
              <text class="iconfont icon-location"></text>
              <!-- 地址 -->
              <text class="info-text">{{projectData?.['6876ff515d31544df2c58975'] || '地址未知'}}</text>
            </view>
            <view class="info-item">
              <text class="iconfont icon-calendar"></text>
             <!-- 开始时间 / 天数 -->
              <text class="info-text">{{(projectData?.['686e317ee9211671b47589db'] || '').slice(0, 10) }} | {{ projectData?.['68a2c8d3703512ca0fc1128c'] || 0 }}天</text>
              <!-- 每日薪资 -->
              <text class="price" v-if="getPositionQuoteStatus(item['686f2308f11e0126aeb367d7']) ">
                {{ Number(getDailySalaryByRole(item)) }}元/人天
              </text>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 底部提交按钮 -->
      <view class="submit-btn-wrapper">
        <button 
          class="submit-btn" 
          @click="showQuotationConfirm"
        >
          {{ !projectStatus ? '提交推荐' : '查看报价' }}
        </button>
      </view>
    </view>
    
    <!-- 加载动画弹窗 -->
    <view class="loading-mask" v-if="isLoading">
      <view class="loading-container">
        <view class="loading-spinner"></view>
        <text class="loading-text">{{loadingText}}</text>
      </view>
    </view>
    
    <!-- 报价确认弹框 -->
    <view class="quotation-modal-mask" v-if="showQuotationModal" @click="closeQuotationModal">
      <view class="quotation-modal" @click.stop>
        <view class="modal-header">
          <text v-if="!projectStatus" class="modal-title">确认报价并提交</text>
          <text v-else class="modal-title">查看报价</text>
        </view>
        
        <view class="modal-content">
          <view class="quotation-list">
            <view 
              v-for="(quotation, index) in projectState" 
              :key="index"
              class="quotation-item"
            >
              <view class="role-header">
                <text class="role-name">{{quotation['68a80c640372283d1e925122']}}</text>
                <text class="role-count">{{quotation['68a80b490372283d1e92510c']}}位</text>
              </view>
              
              <view class="price-info">
                <view class="price-row">
                  <text class="price-label">单人报价</text>
                  <text class="price-value">{{quotation['688b07c92017d222e26dd51a']}}/天</text>
                </view>
                <view class="price-row">
                  <text class="price-label">总报价</text>
                  <text class="price-value">{{quotation['688b07c92017d222e26dd51a'] * quotation['68a80b490372283d1e92510c']}}元</text>
                </view>
              </view>
            </view>
          </view>
          
          <view class="total-section">
            <view class="total-row">
              <text class="total-label">总计</text>
              <text class="total-value">{{totalAmount}}元（含税）</text>
            </view>
          </view>
        </view>
        
        <view class="modal-footer">
          <button v-if="!projectStatus" class="confirm-submit-btn" @click="confirmAndSubmit">
            确认并提交
          </button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { onLoad, onShow } from '@dcloudio/uni-app'
import { ref, watch, computed } from 'vue'
import http from '/pages/utils/request'
import  {apiService, ApiService}  from "/pages/utils/api"
import { useProjectStore } from '/stores/project.js'
import { useUserStore } from '/pages/store/user.js'

const projectData = ref()
const positionList = ref([])

const quotations = ref([])

const status = ref([])

// 报价确认弹框相关数据
const showQuotationModal = ref(false)
const groupedQuotations = ref([])
const totalAmount = ref('0')

const projectStatus = ref()

const ROLE_MAP = new Map([
  ['3b1d641c-7604-4689-982f-6f5fcc03b3b8', '兼职'],
  ['e487029c-c45d-4278-a5f2-8703221ae98f', '礼仪'],
]);

// 获取职位报价状态的函数
const getPositionQuoteStatus = (roleType) => {

  
  // 如果本地没有，再检查服务器状态
  // 空数组或未定义
  if (!Array.isArray(status.value) || status.value.length === 0) return false;

  const getFirst = (val) => Array.isArray(val) ? val[0] : val;

  for (const item of status.value) {
    // 兼容不同返回的 controlId 键：...729f 和 ...729d
    const rawDict = item['68b0182d6b50e0d4f7a7729f'] ?? item['68b0182d6b50e0d4f7a7729d'];
    const dictVal = getFirst(rawDict);
    const rawState = item['68b018b96b50e0d4f7a772e2'];
    const stateVal = getFirst(rawState);
    const mappedRole = ROLE_MAP.get(dictVal) ?? '带队';

    // 角色匹配且状态为"已报价"
    if (mappedRole === roleType && stateVal === 'bf45ad92-e6dc-4922-b2c5-5f6d622055e0') {
      return true;
    }
  }
  return false; // 未匹配到或状态不是"已报价"
}


// 计算属性：判断是否已报价（保持兼容性）
const isQuoted = computed(() => {
  return getPositionQuoteStatus('兼职') // 默认值，实际使用时会被替换
})

// 加载状态
const isLoading = ref(false)
const loadingText = ref('加载中...')

// 使用项目store
const projectStore = useProjectStore()
const userStore = useUserStore()


const projectState = ref([])



  // 获取项目所有保存的报价数据
  const getAllProjectQuotations = () => {
  const quotations = []
  
  // 筛选出当前项目的报价数据
  projectState.value.forEach(item => {
    if (item['68a80c330372283d1e92511a'] === '一类角色') {
      quotations.push({
        roleArr: item['68c108e55f47deca0eb92464'],
        price: item['688b07c92017d222e26dd51a'],
        DetailsId: positionList.value.find(pos => pos['686f2308f11e0126aeb367d7'] === item['68a80c640372283d1e925122']).rowid,
        roleType: item['68a80c640372283d1e925122']
      })
    }
    else{
      quotations.push({
       roleArr: [],
        price: item['688b07c92017d222e26dd51a'],
        DetailsId: positionList.value.find(pos => pos['686f2308f11e0126aeb367d7'] === item['68a80c640372283d1e925122']).rowid,
        roleType: item['68a80c640372283d1e925122']
      })
    }
  })
  return quotations
}


// 清除项目所有保存的报价数据
const clearProjectQuotations = (projectId) => {
  const storageInfo = uni.getStorageInfoSync()
  
  storageInfo.keys.forEach(key => {
    if (key.startsWith(`quotation_${projectId}_`)) {
      uni.removeStorageSync(key)
    }
  })
  console.log('清除项目所有保存的报价数据');
  
}

// 获取卡片背景颜色
const getCardBgColor = (role) => {
  // 安全检查：确保role存在且为字符串
  if (!role || typeof role !== 'string') {
    return '#ffffff'; // 默认白色背景
  }
  
  switch (role) {
    case '礼仪':
      return '#fff8fc'
    case '兼职':
      return '#eef6ff'
    case '带队':
      return '#fff2ee'
    default:
      return '#ffffff'
  }
}

// 处理报价数据分组
const processQuotations = (quotations) => {
  const grouped = {}
  
  quotations.forEach(quotation => {
    const roleType = decodeRoleType(quotation.roleType) // 解码角色类型
    if (!grouped[roleType]) {
      let roleCount = 1 // 默认人数
      let roleArr = []
      
      // 根据角色类型确定人数计算方式
      if (roleType === '带队') {
        // 带队角色：使用min值作为人数
        roleCount = parseFloat(quotation.min) || 1
        roleArr = [{ name: `带队人员 x${roleCount}`, count: roleCount }] // 创建虚拟的roleArr用于显示
      } else {
        // 其他角色：使用roleArr.length
        roleArr = quotation.roleArr || []
        roleCount = roleArr.length || 1
      }
      
      grouped[roleType] = {
        roleType: roleType,
        roleArr: roleArr,
        singlePrice: (parseFloat(quotation.price) / roleCount).toFixed(0),
        totalPrice: quotation.price
      }
    }
  })
  
  return Object.values(grouped)
}

// 显示报价确认弹框
const showQuotationConfirm = () => {
  


  // 检查positionList中的每个角色类别在projectState中是否存在
  const missingRoleTypes = positionList.value.filter(item => {
    const roleType = item['686f2308f11e0126aeb367d7']
    const existsInProjectState = projectState.value.some(state => 
      state['68a80c640372283d1e925122'] === roleType
    )
    return !existsInProjectState
  })

  if (missingRoleTypes.length > 0) {
    console.log('缺失的角色类别:', missingRoleTypes)
    uni.showToast({
      title: '请先完成所有职位报价',
      duration: 2000
    })
    return
  }


  console.log('计算总金额',projectState.value);
  
  // 计算总金额
  totalAmount.value = projectState.value.reduce((sum, item) => sum + parseFloat(item['688b07c92017d222e26dd51a'] || 0), 0).toString()
  
  // 显示弹框
  showQuotationModal.value = true
}

// 关闭报价确认弹框
const closeQuotationModal = () => {
  showQuotationModal.value = false
}

// 确认并提交
const confirmAndSubmit = async () => {
  closeQuotationModal()
  await submitRecommend()
}

const submitRecommend = async () => {
  try {
    // 检查是否所有职位都已报价
    const allQuoted = positionList.value.every(item => 
      getPositionQuoteStatus(item['686f2308f11e0126aeb367d7'])
    )
    
    if (!allQuoted) {
      uni.showToast({
        title: '请先完成所有职位报价',
        icon: 'none',
        duration: 2000
      })
      return
    }
    
    // 获取当前登录用户的rowid
    const userRowid = userStore.rowid || uni.getStorageSync('rowid')
    
    if (!userRowid) {
      uni.showToast({
        title: '请先登录',
        icon: 'none'
      })
      uni.navigateTo({
        url: '/pages/login/login'
      })
      return
    }
    
    if (!projectData.value?.rowid) {
      uni.showToast({
        title: '项目数据异常',
        icon: 'none'
      })
      return
    }
    
    // 读取所有保存的报价数据
    const allQuotations = getAllProjectQuotations(projectData.value.rowid)
    
    // 合并所有报价数据成一个表单
    const mergedQuotationData = {
      projectId: projectData.value.rowid,
      userId: userRowid,
      quotations: allQuotations,
      totalAmount: allQuotations.reduce((sum, item) => sum + parseFloat(item.price || 0), 0)
    }
    
    console.log('合并后的报价数据:', mergedQuotationData)
    
    uni.showLoading({
      title: '提交中...'
    })
    
    // 提交合并后的报价数据
    const res = await apiService.submitRecommend(mergedQuotationData)
    
    uni.hideLoading()
    
    console.log('提交推荐结果:', res)
    

    
    uni.showToast({
      title: '提交成功',
      icon: 'success'
    })
    
    // 提交成功后，延迟跳转回项目首页并刷新数据
    setTimeout(() => {
      // 使用uni.reLaunch确保页面重新加载，刷新数据
      uni.reLaunch({
        url: '/pages/tabs/project/index'
      })
    }, 1500)
    
  } catch (error) {
    console.error('提交推荐失败:', error)
    uni.hideLoading()
    uni.showToast({
      title: '提交失败，请重试',
      icon: 'none'
    })
  }
}

// 添加 URL 解码函数
const decodeRoleType = (encodedRoleType) => {
  try {
    // 直接进行双重解码
    const decoded = decodeURIComponent(decodeURIComponent(encodedRoleType))
    return decoded
  } catch (error) {
    console.warn('解码角色类型失败:', error)
    return encodedRoleType
  }
}

// 根据角色类型获取对应的报价对象
const getQuotationByRoleType = (roleType) => {
  if (!projectData.value?.rowid) return null
  
   const res = projectState.value.find(i => {
     return i['68a80c640372283d1e925122'] === roleType 
    })

    // 添加空值检查，防止未报价时访问undefined的属性
    if (!res) {
      console.log('未找到角色类型的报价数据:', roleType);
      return null;
    }

    console.log('getQuotationByRoleType',res['688b07c92017d222e26dd51a']);
    

  return res['688b07c92017d222e26dd51a'] || null
}

// 根据角色类型获取每日薪资
const getDailySalaryByRole = (item) => {
  console.log('根据角色类型获取每日薪资', item);
  
  if (!projectData.value?.rowid) return 0

  if(item['68917536f6303e511c9ab05f'] === '二类角色'){
    const res = projectState.value.find(i => {
     return i['68a80c640372283d1e925122'] === item['686f2308f11e0126aeb367d7'] 
    })
    // 添加空值检查
    if (!res) {
      console.log('未找到二类角色的报价数据');
      return 0;
    }
    
    return res['688b07c92017d222e26dd51a']/Number(item['686e48ea1f42f2639e1b907b']) || 0
  }
  else{
     const res = projectState.value.find(i => {
     return i['68a80c640372283d1e925122'] === item['686f2308f11e0126aeb367d7']
    })
    if(res){
      console.log('一类角色的报价数据',res);
      
      return res['688b07c92017d222e26dd51a']/Number(item['686e48ea1f42f2639e1b907b']) || 0
    } else {
      console.log('未找到一类角色的报价数据');
      return 0;
    }
  }
}

const getNumPerson = (item) => {
  if (!projectData.value?.rowid) return 0

  if(item['68917536f6303e511c9ab05f'] === '二类角色'){
    console.log('是二类角色喵！');
    
    const res = projectState.value.find(i => {
      console.log(i);
      
       console.log('i',i['68a80c640372283d1e925122']);
       console.log('item',item['686f2308f11e0126aeb367d7']);
       
     return i['68a80c640372283d1e925122'] === item['686f2308f11e0126aeb367d7'] 
    })
    console.log('res',res);
    
    // 添加空值检查
    if (!res) {
      console.log('未找到二类角色的报价数据');
      return 0;
    }
    
    return res['68a80b490372283d1e92510c'] || 0
  }
  else{
    console.log('是一类角色喵！');
     const res = projectState.value.find(i => {
      console.log('i',i['686f2308f11e0126aeb367d7']);
      
     return i['68a80c640372283d1e925122'] === item['686f2308f11e0126aeb367d7']
    })
    console.log('res',res);
    
    if(res){
      return res['688b3d252017d222e26deb47'] || 0
    } else {
      console.log('未找到一类角色的报价数据');
      return 0;
    }
  }
}




// 点击职位卡片跳转到详情页
const handlePositionClick = (item) => {
  // 数据完整性检查
  if (!projectData.value || !item) {
    uni.showToast({
      title: '数据不完整，无法跳转',
      icon: 'none'
    })
    return
  }
  
  try {
    // 获取当前职位的角色类型
    const roleType = item['686f2308f11e0126aeb367d7']
    
    console.log('handlePositionClick 调试信息:')
    console.log('职位角色类型:', roleType)
    console.log('项目ID:', projectData.value.rowid)
    console.log('item',item);
    
    
    
    // 获取对应的报价对象
    const quotationData = getQuotationByRoleType(roleType)
    
    console.log('获取到的报价数据:', quotationData)

    
    // 准备要发送的数据
    const sendData = {
      project: projectData.value,    // 项目完整数据
      position: item,                 // 职位详细数据
      xqNum: item['686e48ea1f42f2639e1b907b'],// 需求人数
      detailsId: item.rowid,  // 使用职位项的rowid
      // 新增：直接传递报价状态
      isQuoted: getPositionQuoteStatus(roleType),
      // 新增：传递对应的报价对象（如果存在）
      quotation: quotationData,
      numperson: getNumPerson(item)
    }

    console.log('sendData');
    console.log(sendData);
    
    // 使用uni.navigateTo的EventChannel特性
    uni.navigateTo({
      url: '/pages/tabs/project/detail/content',
      // 成功跳转后的回调
      success: (res) => {
        console.log('页面跳转成功，准备发送数据')
        
        // 获取EventChannel实例，用于页面间通信
        const eventChannel = res.eventChannel
        
        if (eventChannel && eventChannel.emit) {
          // 通过EventChannel向目标页面发送数据
          // 可以一次性发送多个数据，支持任意复杂度的对象
          eventChannel.emit('acceptProjectData', sendData)
          console.log('数据已通过EventChannel发送')
        } else {
          console.warn('EventChannel不可用，使用本地存储降级')
          uni.setStorageSync('eventChannelData', sendData)
        }
      },
      // 跳转失败的回调
      fail: (err) => {
        console.error('页面跳转失败:', err)
        // 降级使用本地存储
        uni.setStorageSync('eventChannelData', sendData)
        uni.navigateTo({
          url: '/pages/tabs/project/detail/content'
        })
      }
    })
  } catch (error) {
    console.error('EventChannel通信失败:', error)
    // 最终降级方案：使用本地存储
    const roleType = item['686f2308f11e0126aeb367d7']
    const quotationData = getQuotationByRoleType(roleType)
    
    uni.setStorageSync('eventChannelData', {
      project: projectData.value,
      position: item,
       xqNum: item['686e48ea1f42f2639e1b907b'],// 需求人数
      detailsId: item.rowid,  // 使用职位项的rowid
      // 新增：直接传递报价状态
      isQuoted: getPositionQuoteStatus(roleType),
      // 新增：传递对应的报价对象（如果存在）
      quotation: quotationData
    })
    uni.navigateTo({
      url: '/pages/tabs/project/detail/content'
    })
  }
}

const getPositionDetail = async (projectId) => {
    // 显示加载动画
    isLoading.value = true
    loadingText.value = '加载中...'
    
    try {
      const filters = [
          {
            "controlId": "686df6df33681903aca1068e",
            "dataType": 2,
            "spliceType": 1,
            "filterType": 2,
            "value": projectId
          }
        ]
      const res = await apiService.getFilterRows({
        worksheetId:  ApiService.WORKSHEETENUM.PROJECTS,
        filters: filters
      })
      console.log('获取项目详情成功:', res.rows && res.rows[0])

      // rows 为空的健壮性处理
      if (!res || !res.rows || res.rows.length === 0) {
        console.warn('项目详情为空，projectId =', projectId)
        positionList.value = []
        projectData.value = undefined
        return
      }

      projectData.value = res.rows[0]
      console.log('类别');
      console.log(JSON.stringify(JSON.parse(res.rows[0]['686e48ea1f42f2639e1b9074'])[0]['name']));
      
      
      // 将项目标题存储到全局状态
      const projectTitle = projectData.value['686df5d4fa20ded33c042478']
      projectStore.setProjectTitle(projectTitle)
      
      // 设置当前页面导航栏标题
      uni.setNavigationBarTitle({
        title: projectTitle
        })

      const arr = JSON.parse(res.rows[0]['686e48ea1f42f2639e1b9074'])
      console.log('arr');
      console.log(arr);
      console.log('详情：');
      
      // 安全检查：确保arr[0]和sourcevalue存在
      if (arr && arr.length > 0 && arr[0] && arr[0].sourcevalue) {
        try {
          const sourceValue = JSON.parse(arr[0].sourcevalue);
          console.log('详情：', sourceValue);
          console.log('数量：', sourceValue['686e48ea1f42f2639e1b907b']);
        } catch (parseError) {
          console.warn('解析sourcevalue失败:', parseError);
        }
      }
      
      
      // 使用 Promise.all 处理异步数据获取
      const rowidArr = await Promise.all(
        arr.map(async item => {
          try {
            // 安全检查：确保item和sourcevalue存在
            if (!item || !item.sourcevalue) {
              console.warn('item或sourcevalue不存在:', item);
              return null;
            }
            
            const sourceValue = JSON.parse(item.sourcevalue);
            if (!sourceValue || !sourceValue.rowid) {
              console.warn('sourceValue或rowid不存在:', sourceValue);
              return null;
            }
            
            const rowId = sourceValue.rowid;
            const res1 = await apiService.getRowById({
              rowId: rowId,
              worksheetId: ApiService.WORKSHEETENUM.DEMAND
            })
            return res1;
          } catch (error) {
            console.error('处理item时出错:', error, item);
            return null;
          }
        })
      )
      
      // 过滤掉null值
      positionList.value = rowidArr.filter(item => item !== null);


      console.log('rowidArr:');
      console.log(rowidArr);
      
      // 项目详情获取成功后，获取状态信息
      await getStatus()

     await getProjectStatus()

     await initProjectstate()
 
        

      
      // 获取项目所有保存的报价数据
      quotations.value = getAllProjectQuotations(projectData.value.rowid)
      console.log('获取项目所有保存的报价数据:', quotations.value)
      
    } catch (error) {
      console.error('获取项目详情失败:', error)
    } finally {
      // 隐藏加载动画
      isLoading.value = false
    }
}

const getProjectStatus = async () => {
  
 const res = await apiService.getProjectStatus(
  {
    userRowid: userStore.rowid,
    projectId: projectData.value.rowid
  })
  console.log('获取项目状态');
        projectStatus.value = JSON.parse(res.data)['68a6dcc1096ba6d65c502392'] === 'e6c3cc9c-a534-449c-a9e2-ffd7d30b6048'
        
}

const getStatus = async () => {
  console.log('getStatus');
  console.log(userStore.rowid);
  
  try {
    const res = await apiService.getStatus({
      userId: userStore.rowid,
      projectId: projectData.value.rowid
    })

    console.log('res:', res);
    
    // 安全检查：确保res.data存在且不为空
    if (!res || !res.data) {
      console.warn('getStatus返回数据为空');
      status.value = [];
      return;
    }
    
    // 解析数据并获取第一个元素
    const parsedData = JSON.parse(res.data);
    if (Array.isArray(parsedData)) {
      status.value = parsedData;
    } else if (parsedData && typeof parsedData === 'object') {
      // 兼容接口返回单对象的情况
      status.value = [parsedData];
    } else {
      console.warn('parsedData不是数组或对象');
      status.value = [];
    }
    
  } catch (error) {
    console.error('getStatus执行失败:', error);
    status.value = [];
  }
}

const initProjectstate = async () => {
  console.log('初始化数据',[
    projectData.value['686df5d4fa20ded33c042478'],
    uni.getStorageSync('userInfo')['6886e6ba427a9931f8180b02'],
    projectData.value.rowid
  ]);
  
 const res = await apiService.getRowsData({
    worksheetId: '6876257b872d9db2c7ba528d',
    filters: [
      {
        "controlId": "6875c6f31066964a67ef878f",
        "dataType": 2,
        "spliceType": 1,
        "filterType": 2,
        "value": projectData.value['686df5d4fa20ded33c042478']
      },
      {
        "controlId": "68773cef5d31544df2c5cfe0",
        "dataType": 2,
        "spliceType": 1,
        "filterType": 2,
        "value": uni.getStorageSync('userInfo')['6886e6ba427a9931f8180b02']
      }
    ]
  })
  projectState.value = res.rows
  console.log('初始化数据',res.rows);
  
}



// 页面加载时调用API
onLoad((options) => {
  console.log('项目详情页面加载完成', options)
  
  // 初始化用户状态
  userStore.initUserState()

   
  
  if (options.id) {
    console.log('接收到的项目ID:', options.id)
    // 先获取项目详情，然后在回调中获取状态
    getPositionDetail(options.id)
  }
})

// 返回并刷新：在页面显示时检查是否需要刷新
onShow(() => {
  try {
    const refreshProjectId = uni.getStorageSync('refreshPositionProjectId')
    if (!refreshProjectId) return

    const currentId = projectData.value?.rowid
    // 若当前已有同一项目，避免重复拉取详情，仅刷新状态
    if (currentId && currentId === refreshProjectId) {
      console.log('onShow: 仅刷新状态，projectId =', refreshProjectId)
      getStatus()
      initProjectstate()
      return
    }

    // 否则拉取项目详情
    console.log('onShow: 刷新项目详情，projectId =', refreshProjectId)
    getPositionDetail(refreshProjectId)
  } finally {
    // 无论是否刷新，都清理标记，避免重复刷新
    uni.removeStorageSync('refreshPositionProjectId')
    
    // 移除这里的报价数据获取，因为可能projectData还没有数据
    // quotations.value = getAllProjectQuotations(projectData.value.rowid)
    // console.log('onShow: 获取项目所有保存的报价数据');
    // console.log(quotations.value);
  }
})

</script>

<style scoped>
/* 职位详情页面样式 */
.position-container {
  min-height: 100vh;
  background-color: #ffffff;
  padding: 20rpx 30rpx;
  padding-bottom: 150rpx; /* 为底部按钮留出空间 */
  box-sizing: border-box;
}

/* 页面级样式 */
page {
  background-color: #f5f5f5;
}

/* 职位卡片列表 */
.position-list {
  padding: 20rpx 0;
}

/* 职位卡片样式 */
.position-card {
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.position-card:active {
  transform: scale(0.98);
  box-shadow: 0 1rpx 5rpx rgba(0, 0, 0, 0.1);
}

/* 职位标题区域 */
.position-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10rpx;
}

/* 职位标题 */
.position-title {
  display: flex;
  align-items: center;
}

.title-text {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-right: 10rpx;
}

.position-count {
  font-size: 28rpx;
  color: #333;
}

/* 价格标签 */
.price-tag {
  font-size: 24rpx;
  color: #fff;
  background: linear-gradient(to right, #FF6B9B, #FF9E9E);
  padding: 6rpx 20rpx;
  border-radius: 30rpx;
}

/* 已报价样式 */
.reported {
  background: transparent;
  color: #999;
  border: 1px solid #999;
}

/* 职位描述 */
.position-desc {
  font-size: 26rpx;
  color: #666;
  margin-bottom: 20rpx;
  display: flex;
  flex-direction: column;
}

.position-desc text {
  margin-bottom: 5rpx;
}

/* 分隔线 */
.divider {
  height: 1rpx;
  background-color: #EEEEEE;
  margin: 20rpx 0;
}

/* 职位信息区域 */
.position-info {
  display: flex;
  flex-direction: column;
}

/* 信息项 */
.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 10rpx;
  position: relative;
}

/* 图标样式 - 使用伪元素替代实际图标 */
.iconfont {
  width: 30rpx;
  height: 30rpx;
  margin-right: 10rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
}

.icon-location::before {
  content: "📍";
  font-size: 24rpx;
}

.icon-calendar::before {
  content: "📅";
  font-size: 24rpx;
}

/* 信息文本 */
.info-text {
  font-size: 24rpx;
  color: #999;
  flex: 1;
}

/* 价格文本 */
.price {
  font-size: 28rpx;
  color: #FF6B9B;
  font-weight: bold;
}

/* 底部按钮容器 */
.submit-btn-wrapper {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20rpx 30rpx;
  background-color: #f9f8fd;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  z-index: 100;
}

/* 提交按钮 */
.submit-btn {
  width: 100%;
  height: 90rpx;
  line-height: 90rpx;
  text-align: center;
  background: #eb4197;
  color: #fff;
  font-size: 32rpx;
  border-radius: 45rpx;
  border: none;
}

/* 加载动画样式 */
.loading-mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
}

.loading-container {
  background: #FFFFFF;
  border-radius: 24rpx;
  padding: 48rpx 64rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.2);
}

.loading-spinner {
  width: 64rpx;
  height: 64rpx;
  border: 6rpx solid #F0F0F0;
  border-top: 6rpx solid #FF6B9B;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 24rpx;
}

.loading-text {
  font-size: 28rpx;
  color: #333333;
  font-weight: 500;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 报价确认弹框样式 */
.quotation-modal-mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: flex-end;
  justify-content: center;
  z-index: 10000;
  animation: fadeIn 0.3s ease;
}

.quotation-modal {
  width: 100%;
  max-height: 80vh;
  background: #fff;
  border-radius: 24rpx 24rpx 0 0;
  padding: 40rpx 30rpx;
  box-sizing: border-box;
  animation: slideUp 0.3s ease;
  overflow-y: auto;
}

.modal-header {
  text-align: center;
  margin-bottom: 40rpx;
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.modal-title {
  font-size: 36rpx;
  font-weight: 600;
  color: #333;
}

.modal-content {
  margin-bottom: 40rpx;
}

.quotation-list {
  margin-bottom: 30rpx;
}

.quotation-item {
  margin-bottom: 30rpx;
  padding: 20rpx;
  background: #f8f9fa;
  border-radius: 12rpx;
}

.role-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
  padding-bottom: 10rpx;
  border-bottom: 1rpx solid #e9ecef;
}

.role-name {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
}

.role-count {
  font-size: 28rpx;
  color: #666;
}

.price-info {
  display: flex;
  flex-direction: column;
  gap: 15rpx;
}

.price-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.price-label {
  font-size: 28rpx;
  color: #666;
}

.price-value {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
}

.total-section {
  padding: 20rpx;
  background: #fff8fc;
  border-radius: 12rpx;
  border: 1rpx solid #f9cde3;
}

.total-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.total-label {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
}

.total-value {
  font-size: 32rpx;
  font-weight: 600;
  color: #ff6a9c;
}

.modal-footer {
  text-align: center;
}

.confirm-submit-btn {
  width: 100%;
  height: 90rpx;
  line-height: 90rpx;
  background: linear-gradient(to right, #ff6a9c, #ff9e9e);
  color: #fff;
  font-size: 32rpx;
  font-weight: 600;
  border-radius: 45rpx;
  border: none;
  box-shadow: 0 4rpx 12rpx rgba(255, 106, 156, 0.3);
}

.confirm-submit-btn:active {
  transform: scale(0.98);
}

@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

@keyframes slideUp {
  from { transform: translateY(100%); }
  to { transform: translateY(0); }
}
</style>
